package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import decoder.ChineseDecoder;

import model.Saler;
import factory.DaoFactory;

/**
 * Servlet implementation class AddSalerServlet
 */
@WebServlet("/AddSalerServlet")
public class AddSalerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddSalerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.sendRedirect(request.getContextPath() + "/jsp/AddSaler.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		String password = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("password"));
		String password_again = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("password_again"));
		String gender = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("gender"));
		
		int age = 0;
		try {
			age = Integer.parseInt(request.getParameter("age"));
		} catch (NumberFormatException e) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SlrAgeError");
			return;
		}
		
		if (age <= 0) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SlrAgeError");
			return;
		}
		
		String shop = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("shop"));
		
		if (password.equals(password_again)) {
			Saler saler = new Saler(name, password, gender, age, shop);
			
			boolean success = DaoFactory.getSalerDao().save(saler);
			if (success) {
				response.sendRedirect(request.getContextPath() + "/SalerManagementServlet");
			} else {
				response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SlrDatabaseError");
			}
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SlrUnmatchPassword");
		}
		
	}

}
